<?php

namespace App\Http\Middleware;

use App\Traits\ResponseApi;
use Closure;
use Illuminate\Http\Request;

class CheckPermission
{
    use ResponseApi;

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $user = auth('admin')->user();
        // 访问路由
        $route = $request->path();
        $url_arr = explode('/', $route);
        // 根据路由解析权限名称
        if (isset($url_arr[3])) {
            $action = $url_arr[1] . '-' . $url_arr[2] . '-' . $url_arr[3];
        } elseif (isset($url_arr[2])) {
            $action = $url_arr[1] . '-' . $url_arr[2];
        } else {
            $action = $url_arr[1];
        }

        // 验证是否有访问权限
        if ($user->can($action)) {
            return $next($request);
        } else {
            return $this->fail('没有访问权限', 40001);
        }
    }
}
